layui.use(['jquery','layer','table','form','upload'],function () {
    var $ = layui.jquery;
    var layer = layui.layer;
    var table = layui.table;
    var form = layui.form;
    var upload = layui.upload;

    var createTime = "";
    var updateDate = "";

    //刷新页面
    $("#refresh").click(function () {
        location.reload();
    });
    //返回
    $('#goBack').click(function () {
        parent.tabParentChange(3);
    })
    $(document).click(function () {
        parent.$('.rightMenu').hide();
    });

    judge();
    //权限判断 是管理部的才可以增删改的操作
    function judge(){
        var user = localStorage.getItem('user');
        user = JSON.parse(user);
        var userId = user.data.userId;
        $.ajax({
            url: '/product/judgePower',
            type: 'post',
            dataType: 'json',
            data: {'id':userId},
            success: function (data) {
                var power = false;
                var dat = data.data;
                for (var i = 0; i < dat.length; i++) {
                    if(dat[i] == 1){
                        power = true;
                    }
                }
                if(power){
                    treeDemo();
                }else{
                    treeDemoOther();
                }
            }
        })
    }

    //ztree树，不是管理员
    function treeDemoOther(){
        var setting = {
            data: {
                simpleData: {
                    enable: true,  //true 、 false 分别表示 使用 、 不使用 简单数据模式
                    idKey: "acticleCategroyId",   //节点数据中保存唯一标识的属性名称
                    pIdKey: "parentId",    //节点数据中保存其父节点唯一标识的属性名称
                    rootPId: -1  //用于修正根节点父节点数据，即 pIdKey 指定的属性值
                },
                key: {
                    name: "artcleCategroyName"  //zTree 节点数据保存节点名称的属性名称  默认值："name"
                }
            },
            check:{
                enable:true,  //true 、 false 分别表示 显示 、不显示 复选框或单选框
                nocheckInherit:true   //当父节点设置 nocheck = true 时，设置子节点是否自动继承 nocheck = true
            },
            view:{
                showLine: false,
                dblClickExpand :false
            },
            callback :{
                onClick:zTreeOnClick
            },
        };
        var zTree;
        $(document).ready(function(){
            $.ajax({
                url:"/microcircle/getMicrocircleZtree",
                type:"post",
                dataType:"json",
                data:{},
                success:function(data){
                    zTree = $.fn.zTree.init($("#treeDemo"), setting, data.data); //初始化树
                    zTree.expandAll(true);   //true 节点全部展开、false节点收缩
                }
            })
        });

        //点击树节点展示对应分类
        function zTreeOnClick() {
            var nodes = zTree.getSelectedNodes();
            var node = nodes[0];
            var acticleCategroyId = nodes[0].acticleCategroyId;
            if(!node.isParent){
                $.ajax({
                    url: '/microcircle/getMicrocircleZtreeById',
                    type: 'post',
                    dataType: 'json',
                    data: {'acticleCategroyId' : acticleCategroyId,"details" : 3},
                    success: function (data) {
                        demoTable(data.data);
                    }
                })
            }else{
                layer.msg("请选择最小分类类别");
            }
        }
    }

    //ztree树 管理员
    function treeDemo(){
        var setting = {
            data: {
                simpleData: {
                    enable: true,  //true 、 false 分别表示 使用 、 不使用 简单数据模式
                    idKey: "acticleCategroyId",   //节点数据中保存唯一标识的属性名称
                    pIdKey: "parentId",    //节点数据中保存其父节点唯一标识的属性名称
                    rootPId: -1  //用于修正根节点父节点数据，即 pIdKey 指定的属性值
                },
                key: {
                    name: "artcleCategroyName"  //zTree 节点数据保存节点名称的属性名称  默认值："name"
                }
            },
            check:{
                enable:true,  //true 、 false 分别表示 显示 、不显示 复选框或单选框
                nocheckInherit:true   //当父节点设置 nocheck = true 时，设置子节点是否自动继承 nocheck = true
            },
            view:{
                showLine: false,
                dblClickExpand :false
            },
            callback :{
                onRightClick: OnRightClick,
                beforeRename: beforeRename,
                onClick:zTreeOnClick
            },
        };

        //加载树
        var zTree, rMenu;
        $(document).ready(function(){
            $.ajax({
                url:"/microcircle/getMicrocircleZtree",
                type:"post",
                dataType:"json",
                data:{},
                success:function(data){
                    zTree = $.fn.zTree.init($("#treeDemo"), setting, data.data); //初始化树
                    zTree.expandAll(true);   //true 节点全部展开、false节点收缩
                }
            })
            rMenu = $("#rMenu");
        });

        function OnRightClick(event, treeId, treeNode) {
            if (!treeNode && event.target.tagName.toLowerCase() != "button" && $(event.target).parents("a").length == 0) {
                zTree.cancelSelectedNode();
                showRMenu("root", event.clientX, event.clientY);
            } else if (treeNode && !treeNode.noR) {
                zTree.selectNode(treeNode);
                showRMenu("node", event.clientX, event.clientY);
            }
        }
        //修改前判断
        function beforeRename(treeId, treeNode, newName) {
            if (newName.length == 0) {
                alert("节点名称不能为空.");
                var zTree = $.fn.zTree.getZTreeObj("treeDemo");
                setTimeout(function(){zTree.editName(treeNode)}, 10);
                return false;
            }
            return true;
        }
        function showRMenu(type, x, y) {
            $("#rMenu ul").show();
            if (type=="root") {
                $("#m_del").hide();
            } else {
                $("#m_del").show();
            }
            y += document.body.scrollTop;
            x += document.body.scrollLeft;
            y -= 159;
            rMenu.css({"top":y+"px", "left":x+"px", "visibility":"visible"});

            $("body").bind("mousedown", onBodyMouseDown);
        }

        function hideRMenu() {
            if (rMenu) rMenu.css({"visibility": "hidden"});
            $("body").unbind("mousedown", onBodyMouseDown);
        }
        function onBodyMouseDown(event){
            if (!(event.target.id == "rMenu" || $(event.target).parents("#rMenu").length>0)) {
                rMenu.css({"visibility" : "hidden"});
            }
        }

        var user = localStorage.getItem('user');
        user = JSON.parse(user);
        var createId = user.data.userId;
        //添加树节点
        addTreeNode = function addTreeNode() {
            hideRMenu();
            getTime();
            var nodes = zTree.getSelectedNodes(); //获取选中节点的所有数据
            var parentId = nodes[0].acticleCategroyId; //添加节点当前树节点的id，作为添加数据的父节点
            layer.open({
                type:1,
                title:"添加节点",
                area:['400px','220px'],
                shade:0.4,
                offset:['250px','650px'],
                content:"<form class='layui-form'><div class='layui-form-item' style='margin: 20px;'>"+
                    "<label class='layui-input-label'>添加分类：</label>"
                    +"<div class='layui-input-block'>"
                    +"<input type='text' name='name' style='width:220px;height:30px;'id='addNode' lay-verify='required' placeholder='课程分类'>"
                    +"</div>"+"</div></form>",
                btn:['添加','取消'],
                yes:function () {
                    var artcleCategroyName = $("#addNode").val();
                    if(artcleCategroyName.length != 0){
                        $.ajax({
                            url: '/microcircle/addZtreeNode',
                            type: 'post',
                            dataType: 'json',
                            data: {'artcleCategroyName':artcleCategroyName,'createId':createId,'createDate':createTime,'parentId':parentId},
                            success: function (data) {
                                if(data.data){
                                    location.reload();
                                }
                            }
                        })
                    }else {
                        layer.msg("分类名不能为空");
                    }
                }
            })
        }

        //删除树节点
        removeTreeNode = function removeTreeNode() {
            hideRMenu();
            var nodes = zTree.getSelectedNodes();
            var node = nodes[0];
            var acticleCategroyId = nodes[0].acticleCategroyId;

            layer.confirm('确认要删除吗?', {icon: 3, title:'提示'}, function(index){
                if(!node.isParent){
                    if (nodes && nodes.length>0) {
                        $.ajax({
                            url: '/microcircle/delZtreeNode',
                            type: 'post',
                            dataType: 'json',
                            data: {'acticleCategroyId':acticleCategroyId},
                            success: function (data) {
                                if(data.data){
                                    zTree.removeNode(nodes[0]);
                                    layer.msg("删除成功")
                                }
                            }
                        })
                    }
                }else{
                    layer.msg("删除失败！只能删除最小子节点");
                }
            })
        }

        //修改树节点
        edit = function edit() {
            hideRMenu();
            getTime();
            var nodes = zTree.getSelectedNodes();
            var acticleCategroyId = nodes[0].acticleCategroyId;
            layer.open({
                type:1,
                title:"修改节点",
                area:['400px','220px'],
                shade:0.4,
                offset:['250px','650px'],
                content:"<form class='layui-form'><div class='layui-form-item' style='margin: 20px;'>"+
                    "<label class='layui-input-label'>修改分类：</label>"
                    +"<div class='layui-input-block'>"
                    +"<input type='text' name='name' style='width:220px;height:30px;'id='updateNode' lay-verify='required' placeholder='课程分类'>"
                    +"</div>"+"</div></form>",
                btn:['修改','取消'],
                yes:function () {
                    var artcleCategroyName = $("#updateNode").val();
                    if(artcleCategroyName.length != 0){
                        $.ajax({
                            url: '/microcircle/editZtreeNode',
                            type: 'post',
                            dataType: 'json',
                            data: {'acticleCategroyId':acticleCategroyId,'artcleCategroyName':artcleCategroyName,'updateId':createId,'updateDate':updateDate},
                            success: function (data) {
                                if(data.data){
                                    location.reload();
                                }
                            }
                        })
                    }else {
                        layer.msg("分类名不能为空");
                    }
                }
            })
        }

        //点击树节点展示对应分类
        function zTreeOnClick() {
            var nodes = zTree.getSelectedNodes();
            var node = nodes[0];
            var acticleCategroyId = nodes[0].acticleCategroyId;
            if(!node.isParent){
                $.ajax({
                    url: '/microcircle/getMicrocircleZtreeById',
                    type: 'post',
                    dataType: 'json',
                    data: {'acticleCategroyId' : acticleCategroyId,"details" : 3},
                    success: function (data) {
                        demoTable(data.data);
                    }
                })
            }else{
                layer.msg("请选择最小分类类别");
            }
        }

    }

    //数据表格
    getTbale();
    function getTbale() {
        $.ajax({
            url:"/microcircle/getMicrocircleTable",
            type:"post",
            dataType:"json",
            data:{"details" : 3},
            success:function(data){
                demoTable(data.data);
            }
        })
    }

    function demoTable(data) {
        table.render({
            elem:"#demoTable",
            title:"微圈列表",
            data:data,
            toolbar:"#button_ids",
            limit:10,
            page:{//自定义分页布局
                layout:['count','prev','page','next','limit','skip','refresh'],
                limits:[10,20,30],
                first:"首页",
                last:"尾页",
            },
            cols:[[
                {type:"checkbox"},
                {field:"",title:"序号",align:'center',templet:function (data) {
                        return data.LAY_INDEX;
                    }},
                {field:"userName",title:"用户名称",align:'center'},
                {field:"artcleTitle",title:"文章标题",align:'center'},
                {field:"createDate",title:"创建时间",align:'center'},
                {field:"account",title:"用户账号",align:'center'},
                {field:"acticleHits",title:"点击数量",align:'center',templet:function (data) {
                        if(data.acticleHits == null){
                            return "0";
                        }else{
                            return data.acticleHits;
                        }
                    }},
                {field:"acticleLike",title:"点赞数量",align:'center',templet:function (data) {
                        if(data.acticleLike == null){
                            return 0;
                        }else{
                            return data.acticleLike;
                        }
                    }},
                {field:"acticleReviews",title:"评论数量",align:'center',templet:function (data) {
                        if(data.acticleReviews == null){
                            return 0;
                        }else{
                            return data.acticleReviews;
                        }
                    }},
                {field:"acticleShare",title:"分享数量",align:'center',templet:function (data) {
                        if(data.acticleShare == null){
                            return 0;
                        }else{
                            return data.acticleShare;
                        }
                    }},
                {field:'',title:"操作",align:'center',toolbar:"#btnOperation"}
            ]]
        });

    }

    //搜索
    search = function search(){
        var artcleTitle = $("#artcleTitle").val();
        var userName = $("#userName").val();
        var account = $("#account").val();
        getTableSearch(artcleTitle,userName,account);
    }

    //微圈的模糊查询
    getTableSearch = function getTableSearch(artcleTitle,userName,account){
        $.ajax({
            url:"/microcircle/getMicrocircleSearch",
            type:"post",
            dataType:"json",
            data:{'artcleTitle':artcleTitle,'userName': userName,'account':account,"details":3},
            success:function (data) {
                demoTable(data.data);
            }
        })
    };

    //微圈的查看和删除
    table.on("tool(demoTable)",function (obj) {
        if(obj.event == "selectTable"){
            //保存对象数据
            localStorage.setItem("commentMicrocircle",JSON.stringify(obj.data));
            layer.open({
                type:2,
                title:'微圈查看',
                area:['95%','100%'],
                scrollbar: false,
                offset:'auto',
                btn:["确定","取消"],
                content:"microcircle-list-select.html",
                success:function (layero, index) {
                    var data = layero.find('iframe').contents();//获取子页面内容
                    data.find("th[name=artcleTitle]").text(obj.data.artcleTitle);//微圈标题
                    data.find("th[name=userName]").text(obj.data.userName);//创作人
                    data.find("th[name=artcleCategroyName]").text(obj.data.artcleCategroyName);//微圈分类名
                    data.find("th[name=releaseDate]").text(obj.data.releaseDate);//发布时间
                    data.find("th[name=account]").text(obj.data.account);//创建人账号
                    data.find("#article").val(obj.data.article);//文章内容
                    localStorage.setItem("artcleUrl",obj.data.artcleUrl);//文章图片路径
                    if(obj.data.acticleHits == null){
                        data.find("th[name=acticleHits]").text(0);
                    }else{
                        data.find("th[name=acticleHits]").text(obj.data.acticleHits);//文章点击数量
                    }
                    if(obj.data.acticleLike == null){
                        data.find("th[name=acticleLike]").text(0);
                    }else{
                        data.find("th[name=acticleLike]").text(obj.data.acticleLike);//文章点赞数量
                    }
                    if(obj.data.acticleLike == null){
                        data.find("th[name=acticleShare]").text(0);
                    }else{
                        data.find("th[name=acticleShare]").text(obj.data.acticleShare);//文章的分享量
                    }
                    //向微圈操作日志列表添加一条数据
                    var type = 5;
                    var remark = "查看反馈统计";
                    addJsLog(type,remark);
                },
                yes:function (index, layero) {
                    layer.close(index);
                },
                but2:function (index, layero) {
                    layer.close(index);
                }
            })

        }else if(obj.event == "deleteTable"){
            layer.confirm('确定删除当前文章吗?', {icon: 3, title:'删除'}, function(index){
                $.ajax({
                    url:"/microcircle/delMicrocircleBymicrocircleId",
                    data:{"microcircleId":obj.data.microcircleId},
                    type:'post',
                    dataType:'json',
                    success:function (data) {
                        if (data.data == true) {
                            var type = 3;
                            var remark = "删除反馈统计";
                            addJsLog(type,remark);
                            getTbale();
                            //删除对应微圈评论
                            $.ajax({
                                url:"/microcircle/delCommentByCommodityId",
                                data:{"commodityId":obj.data.microcircleId,"type":4},
                                type:"post",
                                dataType:"json",
                                success:function (data) {
                                }
                            });
                            //删除对应的审核信息
                            $.ajax({
                                url:"/microcircle/delCourseRecord",
                                data:{"courseId":obj.data.microcircleId,"type":4},
                                type:"post",
                                dataType:"json",
                                success:function (data) {
                                    layer.msg("删除成功");
                                }
                            });

                        }else{
                            layer.msg("删除失败");
                            getTbale();
                        }
                    }
                });
                layer.close(index);
            })
        }
    })

    //添加操作日志
    function addJsLog(type,remark){
        getTime();
        //向微圈操作日志列表添加一条数据
        var user = localStorage.getItem("user");
        user = JSON.parse(user);
        var tableName = "js_microcircle";
        var param = {
            "tableName":tableName,
            "logType":3,
            "type":type,
            "userId":user.data.userId,
            "createDate":createTime,
            "remark":remark
        };
        $.ajax({
            url:"/microcircle/addMicrocircleLog",
            data:param,
            type:'post',
            dataType:'json',
            success:function (data) {
            }
        });
    }

    //现在时间
    function getTime(){
        var date=new Date();
        var year=date.getFullYear();
        var month=date.getMonth()+1;
        var day=date.getDate();
        var hour=date.getHours();
        var minute=date.getMinutes();
        var second=date.getSeconds();
        var dateStr = year+"-"+zeroFilling(month)+"-"+zeroFilling(day)+" "+zeroFilling(hour)+":"+zeroFilling(minute)+":"+zeroFilling(second);
        updateDate = dateStr;
        createTime = dateStr;
    }
    function zeroFilling(data){
        if(data<10){
            data="0"+data;
        }
        return data;
    }

})